package tictactoe.protocol;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import tictactoe.Client;
import tictactoe.Game;
import tictactoe.Server;
import tictactoe.clientprocessors.SingleClientProcessor;

import java.io.IOException;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by IntelliJ IDEA.
 * User: Double
 * Date: 15.01.12
 * Time: 20:58
 * To change this template use File | Settings | File Templates.
 */
public class Protocol
{
	/*Блок протокольных переменных*/
	public static final String auth = "Auth";
	public static final String getUsers = "GetUsers";
	public static final String setPartner = "SetPartner";
	public static final String answer = "Answer";
	public static final String users = "Users";
	public static final String status = "Status";
	public static final String setPartnerReply = "SetPartnerReply";
	public static final String setPartnerRequest = "SetPartnerRequest";
	public static final String authFail = "AuthFail";
	public static final String authPassed = "AuthPassed";
	public static final String start = "Start";
	public static final String run = "Run";
	private static final String rejected = "Rejected";
	private static final String confirmed = "Confirmed";


	public static synchronized boolean decodeSystemPacket(String inputString, Client client, ArrayList<Client> clients)
	{
		boolean ret = true;
		if(inputString!=null){

			Packet p = null;
			Gson gson = new Gson();
			p = gson.fromJson(inputString,Packet.class);
			if(p.getType().equalsIgnoreCase(Protocol.auth))
			{
				client.setName(p.getData());
				System.out.println(Server.getClientProcessor());
				if(Server.getClientProcessor() instanceof SingleClientProcessor)
				{
					Logger.getLogger("TicTacToeServer").log(Level.SEVERE,"Server.getClientProcessor() is instance of SingleClientProcessor");
					if(Server.getClientProcessor().isValid(client))
					{
						clients.add(client);

						client.sendMsg(Protocol.encode(Protocol.status, Protocol.authPassed));
					}else{
						client.sendMsg(Protocol.encode(Protocol.status, Protocol.authFail));
						try
						{
							client.disconnect();
						} catch (IOException e)
						{
							e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
							Logger.getLogger("TicTacToeServer").log(Level.SEVERE,client.getMessage()+":"+e.getMessage());
						}
					}
					
				}else{
					Server.getClientProcessor().addClient(client);
				}
			}
			else if(p.getType().equalsIgnoreCase(Protocol.getUsers))
			{

				//System.out.println("gson: "+gson.toJson(clients));
					client.sendMsg(encode(Protocol.users, gson.toJson(clients)));

			}
			else if(p.getType().equalsIgnoreCase(Protocol.setPartner))
			{
				for(Client c:clients){
					if(c.getName().equalsIgnoreCase(p.getData()))
					{

							c.sendMsg(encode(Protocol.setPartnerRequest, client.getName()));

						System.out.println("ClientName:" + client.getName() + " Requested player:" + p.getData());
						Logger.getLogger("TicTacToeServer").log(Level.SEVERE,"ClientName:" + client.getName() + " Requested player:" + p.getData());
					}
				}
			}

			else if(p.getType().equalsIgnoreCase(Protocol.answer))
			{
				if(p.getData().contains("yes"))
				{
					String reqName = p.getData().substring(0, p.getData().length() - 4);
					for(Client c:clients){
						if(c.getName().equalsIgnoreCase(reqName))
						{
								c.sendMsg(encode(Protocol.status, Protocol.confirmed));

							c.setPlaying(true);
							client.setPlaying(true);
							Server.getClientProcessor().getClientForGame(client);
							Server.getClientProcessor().getClientForGame(c);
							Server.getGameProcessor().startGame(client,c);
							System.out.println("first: "+client.getName() + " second: "+c.getName());
						}
					}
				}
			}
			else
			{
				ret = false;
			}

		}
		else
		{
			ret = false;
		}

		return ret;
	}
	public static boolean decodeGamePacket(String inputString, Client client, Game game) throws IOException
	{
		boolean ret = true;
		Packet p = null;
		Gson gson = new Gson();
		p = gson.fromJson(inputString,Packet.class);

		if(p.getType().equalsIgnoreCase(Protocol.run))
		{
			System.out.println(client.getName()+": "+client.isTurnFlag());
			if(!game.isVictory() && client.isTurnFlag()){
				System.out.println("Сейчас походил игрок "+client.getName()+" фигурой:"+client.getFigure());
				Logger.getLogger("TicTacToeServer").log(Level.SEVERE,"Сейчас походил игрок "+client.getName()+" фигурой:"+client.getFigure());

				game.makeStep(Integer.parseInt(p.getData()), client.getFigure());
			}
		}else
		{
			ret = false;
		}
		return ret;

	}
	public static String encode(String type, String data)
	{
		String ret;
		Packet p= new Packet(type,data);
		Gson gson = new GsonBuilder().excludeFieldsWithModifiers(Modifier.TRANSIENT).serializeNulls().create();
		ret = gson.toJson(p);
		return ret+"\n";
	}

}
